package com.app.ytong.record;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.app.ytong.R;
import com.app.ytong.basis.BasisActivity;
import com.app.ytong.basis.Constants;
import com.app.ytong.bean.BaseListBean;
import com.app.ytong.bean.BaseListBeanXF;
import com.app.ytong.bean.BasisBean;
import com.app.ytong.bean.GoodsTypeListBean;
import com.app.ytong.bean.LoginBean;
import com.app.ytong.bean.RecordListBean;
import com.app.ytong.bean.RecordListData;
import com.app.ytong.greendao.GreenDaoUtils;
import com.app.ytong.other.PdfScanActivity;
import com.app.ytong.util.MyUtils;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.clj.fastble.data.BleDevice;
import com.jaredrummler.materialspinner.MaterialSpinner;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnLongClick;
import cn.pedant.SweetAlert.SweetAlertDialog;
import my.ActivityTool;
import my.DialogUtils;
import my.TimeUtils;
import my.ViewUtils;
import my.http.MyHttpListener;
import my.http.MyHttpUtils;
import my.http.MyParams;

/**
 * 交易记录
 */
public class RecordListActivity extends BasisActivity {


//    public static void toRecordListActivity(Context context, String id) {
//        Intent intent = new Intent(context, RecordListActivity.class);
//        intent.putExtra("id", id);
//        context.startActivity(intent);
//    }

    public static void toRecordListActivity(Context context,String spinnerType) {
        Intent intent = new Intent(context, RecordListActivity.class);
        intent.putExtra("type", spinnerType);
        context.startActivity(intent);
    }

    @BindView(R.id.recyclerview)
    XRecyclerView mRecyclerView;
    private MyAdapterList mAdapter;
    private RecordListBean mListBean;
    GoodsTypeListBean goodsTypeListBean;
    String id;
    String spinnerType;

    @BindView(R.id.text_start_time)
    TextView textStartTime;
    @BindView(R.id.text_end_time)
    TextView textEndTime;
    Calendar calendarStart;
    Calendar calendarEnd;

    @BindView(R.id.spinner)
    MaterialSpinner spinner;


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void initViews() {
        setContentView(R.layout.record_list_activity);
        setTitle("交易记录");
        setTitleBg(R.color.base_blue);
        setTitleLeftButton(null);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setVerticalScrollBarEnabled(true);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        mRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
        mRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                mListBean.refresh();
                getList();
            }

            @Override
            public void onLoadMore() {
                getList();
            }
        });
        mRecyclerView.setPullRefreshEnabled(true);
        mRecyclerView.setLoadingMoreEnabled(true);
        initCalendar();
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        spinnerType = getIntent().getStringExtra("type");
        if (TextUtils.isEmpty(spinnerType)) {
            spinnerType = "other";
        }

        mListBean = new RecordListBean();
        setListView();
        setTitleLeftButton(null);

        if(spinnerType.equals("chaqing")){
            spinner.setItems(getResources().getStringArray(R.array.isgua));
            spinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
                @Override public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
                    mRecyclerView.refresh();
                }
            });
        }else {
            goodsTypeListBean = GreenDaoUtils.getGoodsTypeListBeanAndInit();
            spinner.setItems(goodsTypeListBean.getAllName());
            spinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {

                @Override public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
                    mRecyclerView.refresh();
                }
            });
        }
        getList();
    }

    private void  initCalendar(){
        calendarStart = Calendar.getInstance();
//        calendarStart.add(Calendar.MONTH, 0);
//        calendarStart.set(Calendar.DAY_OF_MONTH, 1);
        calendarStart.set(Calendar.HOUR_OF_DAY,0);
        calendarStart.set(Calendar.MINUTE,0);
        calendarStart.set(Calendar.SECOND,0);
        calendarStart.set(Calendar.MILLISECOND,0);

        calendarEnd = Calendar.getInstance();
        calendarEnd.set(Calendar.HOUR_OF_DAY,0);
        calendarEnd.set(Calendar.MINUTE,0);
        calendarEnd.set(Calendar.SECOND,0);
        calendarEnd.set(Calendar.MILLISECOND,0);
        textStartTime.setText(calendarStart == null? "": TimeUtils.getTimeByDate(calendarStart.getTime(), "yyyy-MM-dd"));
        textEndTime.setText(calendarEnd == null? "":TimeUtils.getTimeByDate(calendarEnd.getTime(), "yyyy-MM-dd"));
    }

    private void setListView() {
        if (mAdapter == null) {
            mAdapter = new MyAdapterList();
            mRecyclerView.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
    }

    private void onListViewComplete() {
        mRecyclerView.refreshComplete();
        mRecyclerView.loadMoreComplete();
        mRecyclerView.setLoadingMoreEnabled(mListBean.hasNextPage());
//        mRecyclerView.setLoadingMoreEnabled(false);
        setEmptyView();
    }

    private void setEmptyView() {
        if (mListBean == null || mListBean.getList().size() == 0) {
            findViewById(R.id.refresh_view).setVisibility(View.VISIBLE);
            findViewById(R.id.refresh_view).setOnClickListener(
                    new View.OnClickListener() {
                        public void onClick(View v) {
                            mRecyclerView.refresh();
                        }
                    });
        } else {
            findViewById(R.id.refresh_view).setVisibility(View.INVISIBLE);
        }
    }



    private void getList() {
        MyParams params = new MyParams();
        showProgress();
        params.put("aid", LoginBean.getInstance().getAid());
        params.put("bstime", textStartTime.getText().toString().trim());
        params.put("betime", textEndTime.getText().toString().trim());
        params.put("fsg", MyUtils.getPutTabSelectId());
        params.put("ifs", MyUtils.getHomeSelectId());
        if(spinnerType.equals("chaqing")){
            if(spinner.getSelectedIndex()!=0){
                params.put("sty",spinner.getSelectedIndex());
            }
        }else {
            params.put("tid", goodsTypeListBean.getTidByPosition(spinner.getSelectedIndex()));
        }
        params.put(BaseListBeanXF.PAGE_NAME, mListBean.getNextPage());
        params.put(BaseListBeanXF.PAGE_SIZE_NAME, BaseListBeanXF.PAGE_SIZE);
        String url ="";
        if(MyUtils.getTabSelectName().contains("入")){
            url = Constants.URL_INSTOCK_SELECT_ALL;
        }else {
            url = Constants.URL_OUTSTOCK_SELECT_ALL;
        }

        MyHttpUtils.get(url, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        if (isFinishing()) return;
                        RecordListBean recordListBean = (RecordListBean) result;
                        mListBean.addListBean(recordListBean);
                        setListView();
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
                        if (isFinishing()) return;
                        mListBean.getList().clear();
                        setListView();
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        if (isFinishing()) return;
                        dismissProgress();
                        onListViewComplete();
                    }
                },
                0, RecordListBean.class);

    }

    public class MyAdapterList extends RecyclerView.Adapter<RecyclerView.ViewHolder> {


        public MyAdapterList() {
        }

        //创建新View，被LayoutManager所调用
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            if (viewType == TYPE_CONTENT) {
                View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.record_list_item, viewGroup, false);
                return new ViewHolder(view);
            } else {
                View viewFoot = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.record_foot, viewGroup, false);
                return new FootHolder(viewFoot);
            }
        }

        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
            if (viewHolder instanceof ViewHolder) { // 内容
                ((ViewHolder) viewHolder).bind(position);
            } else { // 尾部
                ((FootHolder) viewHolder).bind(position);
            }
        }

        private static final int TYPE_CONTENT = 0, TYPE_FOOTER = 1;

        @Override
        public int getItemViewType(int position) {
//            return super.getItemViewType(position);
            return (position == (getItemCount() - 1)) ? TYPE_FOOTER : TYPE_CONTENT;
        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            return mListBean == null ? 0 : (mListBean.getList().size() + 1);
        }

        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.list_item)
            public View list_item;
            @BindView(R.id.text_no)
            public TextView text_no;
            @BindView(R.id.text_mid)
            public TextView text_mid;
            @BindView(R.id.text_wno)        //单号
            public TextView text_wno;
            @BindView(R.id.text_buy_or_sup)
            public TextView text_buy_or_sup;
            @BindView(R.id.text_cna)
            public TextView text_cna;
            @BindView(R.id.text_gwt)
            public TextView text_gwt;
            @BindView(R.id.text_total)
            public TextView text_total;


            public ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
            }

            public void bind(int position) {
                RecordListData data = mListBean.getList().get(position);
                MyUtils.setNotNullText(text_no,""+(position+1));
                MyUtils.setNotNullText(text_wno,""+data.getWno());
                MyUtils.setNotNullText(text_mid,""+data.getMid());
                if(MyUtils.getTabSelectName().contains("出")){
                    text_buy_or_sup.setText("客户");
                }

                MyUtils.setNotNullText(text_cna,""+data.getCna());
                MyUtils.setNotNullText(text_total,""+data.getTotal()+"元");
                MyUtils.setNotNullText(text_gwt,""+data.getGwt()+"斤");
                list_item.setTag(data);
            }

            @OnClick(R.id.list_item)
            public void onItemClick(View v) {
                RecordListData data = (RecordListData) v.getTag();
                Bundle extras = new Bundle();
                extras.putString("mid", data.getMid());
                if(!spinnerType.equals("chaqing")){
                    extras.putString("tid",goodsTypeListBean.getTidByPosition(spinner.getSelectedIndex()));
                }
                ActivityTool.skipActivityForResult(mContext,RecordInfoActivity.class,extras,WARNLISTRESULT);
            }

            @OnLongClick(R.id.list_item)
            public boolean onItemLongClick(View v) {
                RecordListData data = (RecordListData) v.getTag();
                DialogUtils.showWarningDialog(mContext,"是否删除","确定", new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                        MyParams params = new MyParams();
                        showProgress();
                        params.put("aid", LoginBean.getInstance().getAid());
                        params.put("fsg", MyUtils.getPutTabSelectId());
                        params.put("mid", data.getMid());

                        String url ="";
                        if(MyUtils.getTabSelectName().contains("入")){
                            url = Constants.URL_INSTOCK_DELETE_BATCH;
                        }else {
                            url = Constants.URL_OUTSTOCK_DELETE_BATCH;
                        }

                        MyHttpUtils.delete(url, params, new MyHttpListener() {
                                    @Override
                                    public void onSuccess(int httpWhat, Object result) {
                                        if (isFinishing()) return;
                                        BasisBean basisBean = (BasisBean) result;
                                        showToast(basisBean.getStatusInfo());
                                        mListBean.getList().remove(data);
                                        notifyDataSetChanged();
                                    }

                                    @Override
                                    public void onFailure(int httpWhat, Object result) {
                                        super.onFailure(httpWhat, result);
                                    }

                                    @Override
                                    public void onFinish(int httpWhat) {
                                        dismissProgress();
                                    }
                                },
                                0, BasisBean.class);
                    }
                });


                return true;
            }

        }

        // 尾部
        public class FootHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.text_all_sje)
            public TextView text_all_sje;
            @BindView(R.id.text_all_gwt)
            public TextView text_all_gwt;

            public FootHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);

            }

            public void bind(int position) {
                text_all_sje.setText(mListBean.getAllMoney()+"元");
                text_all_gwt.setText(mListBean.getAllWeight()+"斤");
            }

            @OnClick(R.id.list_item)
            public void onBtnSave() {

            }

        }
    }


    public final static int WARNLISTRESULT = 44;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == WARNLISTRESULT){
            mListBean.refresh();
            getList();
        }
    }

    @OnClick(R.id.view_filter_1)
    void timeBeginChoose() {
        //时间选择器
        TimePickerView pvTime = new TimePickerBuilder(mContext, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                if (calendarStart == null) {
                    calendarStart = Calendar.getInstance();
                }
                calendarStart.setTime(date);
                onTimeBeginChoosed();
            }
        })
                .addOnCancelClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                    }
                })
                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .build();
        pvTime.show();
        ViewUtils.hideInput(mContext);
    }


    void onTimeBeginChoosed() {
        textStartTime.setText(calendarStart == null? "":TimeUtils.getTimeByDate(calendarStart.getTime(), "yyyy-MM-dd"));
        if(calendarStart != null && calendarEnd != null){
            mRecyclerView.refresh();
        }else if(calendarStart == null && calendarEnd == null){
            mRecyclerView.refresh();
        }
    }

    @OnClick(R.id.view_filter_2)
    void timeEndChoose() {
        //时间选择器
        TimePickerView pvTime = new TimePickerBuilder(mContext, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                if (calendarEnd == null) {
                    calendarEnd = Calendar.getInstance();
                }
                calendarEnd.setTime(date);
                onTimeEndChoosed();
            }
        }).addOnCancelClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .build();
        pvTime.show();
        ViewUtils.hideInput(mContext);
    }

    void onTimeEndChoosed() {
        textEndTime.setText(calendarEnd == null? "":TimeUtils.getTimeByDate(calendarEnd.getTime(), "yyyy-MM-dd"));
        if(calendarStart != null && calendarEnd != null){
            mRecyclerView.refresh();
        }else if(calendarStart == null && calendarEnd == null){
            mRecyclerView.refresh();
        }
    }

}
